package com.itheima.common;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.UUID;

public class JwtToken {

    //存活时间毫秒值
    private static long time = 1000 * 60 * 60*24;
    //定义解析密匙
    private static String signature = "user";
    public static String jwt(String str) {
        //创建jwt加密器
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                //定义jwt头文件
                .setHeaderParam("typ", "jwt")
                .setHeaderParam("alg", "hs256")
                //定义jwt的荷载
                .claim("token", str)

                //设置死亡时间（当前系统时间+存活时间）
                .setExpiration(new Date(System.currentTimeMillis() + time))
                //设置随机UUID
                .setId(UUID.randomUUID().toString())
                //定义加密令牌锁
                .signWith(SignatureAlgorithm.HS256, signature)
                .compact();
        return jwtToken;
    }
    public static String parse(String token){

        //获取解析器
        JwtParser jwtParser = Jwts.parser();
        //写入解析密匙与解析对象，返回一个Claims的数组
        Jws<Claims> claimsJws = jwtParser
                .setSigningKey("user")
                .parseClaimsJws(token);
        //获取对象实体
        Claims claims = claimsJws.getBody();
        System.out.println(claims);
        return claims.toString();

    }

    public static boolean verifyToken(String token){
        if (StringUtils.isEmpty(token)){
            return  false;
        }
        try {
            parse(token);
        } catch (Exception e) {
           return false;
        }
        return true;
    }



}
